/**
 * @format
 * @Author: TC
 * @Date: 2021-09-27 15:15:38
 * @Last Modified by: TC
 * @Last Modified time: 2023-03-26 02:05:56
 */

import { AudioClip, AudioSource } from "cc";
import { app } from "../App";

/**
 * 音频管理
 */
export class AudioManager {
    private musicAs: AudioSource = new AudioSource();
    private effectAs: AudioSource = new AudioSource();
    private _musicVolume: number = 1;
    private _effectVolume: number = 1;

    /**
     * 播放背景音乐
     * @param bundleName 包名
     * @param musicPath 音乐资源路径
     * @param bLoop 是否循环
     * @returns
     */
    public playMusic(bundleName: string, musicPath: string, bLoop: boolean = true) {
        this.musicAs.stop();
        app.resMgr.loadAudio(bundleName, musicPath, (musicRes: AudioClip) => {
            this.musicAs.volume = this._musicVolume;
            this.musicAs.clip = musicRes;
            this.musicAs.loop = bLoop;
            this.musicAs.play();
        });
    }

    /**
     * 设置背景音乐音量
     * @param val 音量
     */
    public setMusicVal(val: number): void {
        this._musicVolume = val;
        this.musicAs.volume = val;
    }

    /**
     * 获取背景音乐音量
     * @returns
     */
    public getMusicVal(): number {
        return this._musicVolume;
    }

    /**
     * 停止背景音乐
     */
    public stopMusic(): void {
        this.musicAs.stop();
    }

    /**
     * 暂停背景音乐
     */
    public pauseMusic(): void {
        this.musicAs.pause();
    }

    /**
     * 恢复背景音乐
     */
    public resumeMusic(): void {
        this.musicAs.play();
    }

    /**
     * 背景音乐是否在播放
     */
    public get musicPlaying(): boolean {
        return this.musicAs.playing;
    }

    /**
     * 播放音效
     * @param bundleName 包名
     * @param effectPath 音效资源名称
     * @param volumeScale 音量缩放
     */
    public playEffect(bundleName: string, effectPath: string, volumeScale?: number): void {
        app.resMgr.loadAudio(bundleName, effectPath, (effectRes: AudioClip) => {
            this.musicAs.volume = this._effectVolume;
            this.effectAs.playOneShot(effectRes, volumeScale);
        });
    }

    /**
     * 设置音效音量
     * @param val 音量
     */
    public setEffectVal(val: number): void {
        this._effectVolume = val;
        this.effectAs.volume = val;
    }

    /**
     * 获取音效音量
     * @returns
     */
    public getEffectVal(): number {
        return this._effectVolume;
    }
}
